//
//  WDNativeManager.m
//  WDPolymerizeSDK
//
//  Created by little People on 2023/5/31.
//

#import "WDNativeManager.h"
#import "WDAdStatusManager.h"
#import "WDNativeModel.h"
#import "WDNativeViewController.h"
#import "WDBMSModel.h"
#import "WDCallBackManager.h"
#import "WDAdStatusManager.h"
@import GoogleMobileAds;
@interface WDNativeManager () <GADNativeAdLoaderDelegate, GADVideoControllerDelegate, WDNativeViewControllerDelegate>

/// You must keep a strong reference to the GADAdLoader during the ad loading
/// process.
@property(nonatomic, strong) GADAdLoader *adLoader;

/// The native ad view that is being presented.
@property(nonatomic, strong) GADNativeAdView *nativeAdView;

/// The height constraint applied to the ad view, where necessary.
@property(nonatomic, strong) NSLayoutConstraint *heightConstraint;

@property (nonatomic, strong)WDNativeViewController *nativeVC;

@property(nonatomic, strong) GADNativeAd *nativeAd;

@property (nonatomic, assign) BOOL hasShowAd;
@end

@implementation WDNativeManager
static WDNativeManager *_native = nil;
+ (instancetype)shareNative{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _native = [[self alloc] init];
        _native.nativeIDIndex = 0;
    });
    return _native;
}

- (NSString *)getAdUnitID
{
    if ([WDBMSModel shareBMSModel].nativeID.count > 0)
    {
        if (self.nativeIDIndex > [WDBMSModel shareBMSModel].nativeID.count)
        {
            self.nativeIDIndex = 0;
        }
        NSArray *temp = [WDBMSModel shareBMSModel].nativeID[self.nativeIDIndex];
        NSString *nid = temp[1];
        self.nativeIDIndex++;
        if (nid)
        {
            return nid;
        }
    }
    return @"";
}

- (void)loadNativeAd
{
    
//    NSString *nid = @"ca-app-pub-3940256099942544/3986624511";
    NSString *nid = [self getAdUnitID];
    if (nid.length <= 0)
    {
        WDLog(@"no native id");
        return;
    }
    WDLog(@"native id:%@",nid);
    [[WDAdStatusManager shareStatusManager] adLoadWithEventName:NATIVE_EVENT_NAME];
    GADMultipleAdsAdLoaderOptions *multipleAdsOptions =
          [[GADMultipleAdsAdLoaderOptions alloc] init];
      multipleAdsOptions.numberOfAds = 1;
      self.adLoader = [[GADAdLoader alloc]
            initWithAdUnitID:nid
          rootViewController:self.nativeVC
                     adTypes:@[ GADAdLoaderAdTypeNative ]
                     options:@[ multipleAdsOptions ]];

      self.adLoader.delegate = self;
      [self.adLoader loadRequest:[GADRequest request]];
}

- (void)reLoad
{
    double delayInSeconds = 5.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [self loadNativeAd];
    });
}

- (void)showNativeAd:(BOOL)isCard isJsonSource:(BOOL)isJsonSource
{
    
    if (!self.isLoadNative)
    {
        self.hasShowAd = YES;
        WDLog(@"没有native ad，等待重新加载");
        [[WDCallBackManager shareCallBackManager] adCallBackWithType:ShowFail adSpace:[WDCallBackModel shareCallBackModel].adSpace message:@"no native ad"];
        [self reLoad];
        return;
    }

    [[WDAdStatusManager shareStatusManager] adRequestWithEventName:NATIVE_EVENT_NAME];
    [[WDAdStatusManager shareStatusManager] adShowWithEventName:NATIVE_EVENT_NAME];
    [[WDCallBackManager shareCallBackManager] adCallBackWithType:Show adSpace:[WDCallBackModel shareCallBackModel].adSpace message:@""];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        self.nativeVC = [[WDNativeViewController alloc] init];
        self.nativeVC.delegate = self;
        self.nativeVC.isCardAd = isCard;
        self.nativeVC.isJsonSource = isJsonSource;
        UIViewController *rootViewController = [[[UIApplication sharedApplication].windows objectAtIndex:0] rootViewController];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:self.nativeVC];
        [nav setNavigationBarHidden:YES animated:NO];
        nav.interactivePopGestureRecognizer.enabled = NO;
        rootViewController.definesPresentationContext = YES;
        nav.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        [rootViewController presentViewController:nav animated:NO completion:nil];
    });
    
}



- (void)adLoader:(nonnull GADAdLoader *)adLoader didFailToReceiveAdWithError:(nonnull NSError *)error {
    WDLog(@"adLoader fail:%@",error.localizedDescription);
    [[WDAdStatusManager shareStatusManager] adLoadFailedWithCode:error.code message:error.localizedDescription eventName:NATIVE_EVENT_NAME];
    [[WDAdStatusManager shareStatusManager] adLoadFillFailedWithEventName:NATIVE_EVENT_NAME];
    self.isLoadNative = NO;
    [self reLoad];
}

- (void)adLoader:(nonnull GADAdLoader *)adLoader didReceiveNativeAd:(nonnull GADNativeAd *)nativeAd {
    [[WDAdStatusManager shareStatusManager] adLoadFillSuccessWithEventName:NATIVE_EVENT_NAME];
    __weak WDNativeManager *weakSelf = self;
    self.nativeAd = nativeAd;
    nativeAd.paidEventHandler = ^(GADAdValue * _Nonnull value) {
        WDNativeManager *strongSelf = weakSelf;
        NSDecimalNumber *value1 = value.value;
        NSString *currencyCode = value.currencyCode;
        GADAdValuePrecision precision = value.precision;
        
        
        WDLog(@"paidEventHandler value1:%@,currencyCode:%@,precision:%ld",value1,currencyCode,(long)precision);
        
        // Get the ad unit ID.
//                NSString *adUnitId = strongSelf.openAd.adUnitID;
        
        GADAdNetworkResponseInfo *loadedAdNetworkResponseInfo = strongSelf.nativeAd.responseInfo.loadedAdNetworkResponseInfo;
        NSString *adSourceName = loadedAdNetworkResponseInfo.adSourceName;
        NSString *adSourceID = loadedAdNetworkResponseInfo.adSourceID;
        NSString *adSourceInstanceName = loadedAdNetworkResponseInfo.adSourceInstanceName;
        NSString *adSourceInstanceID = loadedAdNetworkResponseInfo.adSourceInstanceID;
        NSDictionary<NSString *, id> *extras = strongSelf.nativeAd.responseInfo.extrasDictionary;
        
        
        [[WDAdStatusManager shareStatusManager] adRevenue:@"navive" source:@"admob" revenue:[NSString stringWithFormat:@"%@",value.value] currency:currencyCode];
        
        WDLog(@"paidEventHandler2 adSourceName:%@,adSourceID:%@,adSourceInstanceName:%@,adSourceInstanceID:%@,extras:%@",adSourceName,adSourceID,adSourceInstanceName,adSourceInstanceID,extras);
        
    };
    
    self.isLoadNative = YES;
    WDLog(@"1Received native ad: %@", nativeAd.headline);
    WDLog(@"2Received native ad: %@", nativeAd.callToAction);
    WDLog(@"3Received native ad: %@", nativeAd.body);
    WDLog(@"3Received native ad: %@", nativeAd.store);
    WDLog(@"4Received native ad: %@", nativeAd.advertiser);
    WDLog(@"5Received native ad: %@", nativeAd.icon.imageURL);
    WDLog(@"6Received native ad: %@", nativeAd.icon.image);
    WDLog(@"7Received native ad: %@", nativeAd.images);
    WDLog(@"8Received native ad: %@", nativeAd.starRating);
    WDLog(@"9Received native ad: %@", nativeAd.mediaContent);
    WDLog(@"10Received native ad: %@", nativeAd.price);
    WDNativeModel *model = [WDNativeModel shareNativeModel];
    model.nativeAd = nativeAd;
    model.headline = nativeAd.headline;
    model.callToAction = nativeAd.callToAction;
    model.body = nativeAd.body;
    model.store = nativeAd.store;
    model.advertiser = nativeAd.advertiser;
    
    model.mediaContent = nativeAd.mediaContent;
    
    model.images = [NSMutableArray array];
    if (nativeAd.mediaContent.hasVideoContent)
    {
        model.isMedia = YES;
        
    }
    else{
        model.isMedia = NO;
//        for (GADNativeAdImage *im in nativeAd.images) {
//            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//                NSData *d = [[NSData alloc]initWithContentsOfURL:im.imageURL];
//                UIImage *temp = [UIImage imageWithData:d];
//                [model.images addObject:temp];
//            });
//
//        }
    }
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSData *data = [[NSData alloc]initWithContentsOfURL:nativeAd.icon.imageURL];
        model.iconImage = [UIImage imageWithData:data];
    });
    
    model.starImageName = [self imageNameForStars:nativeAd.starRating];
    model.price = nativeAd.price;
    if (self.adLoaderCallBackBlcok)
    {
        self.adLoaderCallBackBlcok();
    }
    if (self.hasShowAd)
    {
        self.hasShowAd = NO;
        [self showNativeAd:NO isJsonSource:NO];
    }
}

- (NSString *)imageNameForStars:(NSDecimalNumber *)numberOfStars {
  double starRating = numberOfStars.doubleValue;
  if (starRating >= 5) {
    return @"stars_5";
  } else if (starRating >= 4.5) {
    return @"stars_4_5";
  } else if (starRating >= 4) {
    return @"stars_4";
  } else if (starRating >= 3.5) {
    return @"stars_3_5";
  }
    return @"";
}


- (void)dismiss
{
    [[WDAdStatusManager shareStatusManager] adCloseWithEventName:NATIVE_EVENT_NAME];
    self.hasShowAd = NO;
    [[WDCallBackManager shareCallBackManager] adCallBackWithType:Finish adSpace:[WDCallBackModel shareCallBackModel].adSpace message:@""];
    if (self.nativeVC)
    {
        self.nativeVC.delegate = nil;
        self.nativeVC = nil;
    }
    
    self.adLoaderCallBackBlcok = nil;
    self.isLoadNative = NO;
    [self loadNativeAd];
}



@end
